import {
  isBindByDeviceSn,
  memberBindDev,
  getMemberDeviceById,
} from '@src/api/member';
import {
  storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import member from "@src/store/member";
import base from "@src/store/base";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'myPageBanners', 'myPageBg', 'perms']
  }],
  properties: {
    memberId: {
      type: Number,
      value: ''
    },
    bindDevice: {
      type: Array,
      value: []
    }
  },
  data: {
    showDialog: false,
    snCode: '',
    errMsg: ''
  },
  methods: {
    open() {
      this.setData({
        showDialog: true
      })
    },
    async comfirm() {
      await this.verifySncode()
      let {
        errMsg,
        snCode,
        memberId,
        bindDevice
      } = this.data
      if (errMsg) {
        return false
      }
      memberBindDev({
        memberId,
        deviceSn: snCode
      }).then(res => {
        res.code == 0 && res.data && this.close()
        wx.showModal({
          showCancel: false,
          title: '绑定设备SN',
          content: '绑定成功',
          confirmColor: this.data.themeColor,
          success: (res => {
            res.confirm && this.triggerEvent('changeData')
          })
        })
      })

    },
    close() {
      this.setData({
        showDialog: false,
        snCode: '',
        errMsg: ''
      })
    },
    async verifySncode() {
      this.setData({
        errMsg: ''
      })
      let {
        snCode,
        memberId
      } = this.data
      if (!snCode) {
        this.setData({
          errMsg: '请输入SN码'
        })
        return
      }
      if (!/^[A-Za-z0-9]{1,30}$/.test(snCode)) {
        this.setData({
          errMsg: '请输入符合格式的SN码，仅支持最长30个数字、字母'
        })
        return
      }
      let result = await isBindByDeviceSn({
        deviceSn: snCode,
        memberId
      })
      if (result.code == 0 && (result.data == 2 || result.data == 3)) {
        this.setData({
          errMsg: '绑定失败，该设备SN已被绑定'
        })
        return
      }

    },
    bindKeyInput(e) {
      const {
        value
      } = e.detail
      const {
        key
      } = e.currentTarget.dataset
      this.setData({
        [key]: value
      })
    },
    openCamera() {
      wx.scanCode({
        success: (res) => {
          this.setData({
            snCode: res.result
          })
        }
      })
    }
  }
})